package cn.highset.modules.base.controller.api;

import cn.highset.base.ApiBaseController;
import cn.highset.common.annotation.IgnoreAuth;
import cn.highset.common.utils.CommonUtil;
import cn.highset.common.utils.PageUtil;
import cn.highset.common.utils.ResultUtil;
import cn.highset.common.utils.SecurityUtil;
import cn.highset.common.vo.PageVo;
import cn.highset.common.vo.Result;
import cn.highset.common.vo.SearchVo;
import cn.highset.modules.base.entity.Vote;
import cn.highset.modules.base.entity.VoteItem;
import cn.highset.modules.base.entity.VoteItemPraise;
import cn.highset.modules.base.service.VoteItemPraiseService;
import cn.highset.modules.base.service.VoteItemService;
import cn.highset.modules.base.service.VoteService;
import cn.highset.modules.base.service.mybatis.IVoteItemPraiseService;
import cn.highset.modules.base.service.mybatis.IVoteItemService;
import cn.highset.redis.client.RedisClient;
import cn.hutool.core.collection.CollUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.Date;
import java.util.Set;

/**
 * 类 描 述：API 投票活动信息
 * 创建时间：2019-06-15 10:32
 * 创 建 人：victor
 */
@Slf4j
@RestController
@Api(description = "API投票活动信息")
@RequestMapping("/api/vote")
@Transactional
public class ApiVoteController extends ApiBaseController {

    @Autowired
    private VoteService voteService;
    @Autowired
    private VoteItemService voteItemService;
    @Autowired
    private VoteItemPraiseService voteItemPraiseService;
    @Autowired
    private IVoteItemService iVoteItemService;
    @PersistenceContext
    private EntityManager entityManager;
    @Autowired
    private SecurityUtil securityUtil;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private IVoteItemPraiseService iVoteItemPraiseService;

    @ApiOperation(value = "获取投票活动列表")
    @IgnoreAuth
    @PostMapping("list")
    public Result<Page<Vote>> list(@ModelAttribute Vote vote,
                                   @ModelAttribute SearchVo searchVo,
                                   @ModelAttribute PageVo pageVo) {
        Page<Vote> page = voteService.findByCondition(vote, searchVo, PageUtil.initPage(pageVo));
        page.getContent().forEach(e -> {
            e.setDate(CommonUtil.getShowDate(e.getTimeStart(), e.getTimeEnd(),false));
            entityManager.clear();
        });
        return new ResultUtil<Page<Vote>>().setData(page);
    }

    @ApiOperation(value = "获取投票活动明细列表")
    @IgnoreAuth
    @PostMapping("itemList")
    public Result<Page<VoteItem>> itemList(@ModelAttribute VoteItem voteItem,
                                           @ModelAttribute SearchVo searchVo,
                                           @ModelAttribute PageVo pageVo) {
        Page<VoteItem> page = voteItemService.findByCondition(voteItem, searchVo, PageUtil.initPage(pageVo));
        return new ResultUtil<Page<VoteItem>>().setData(page);
    }


    @ApiOperation(value = "投票")
    @PostMapping("praise/{voteId}/{voteItemid}")
    public Result<Object> collect(@PathVariable("voteId") String voteId, @PathVariable("voteItemid") String voteItemid) {
        Vote vote = voteService.findById(voteId);
        if (vote == null) {
            return new ResultUtil<Object>().setErrorMsg("投票活动不存在");
        }
        if (new Date().compareTo(vote.getTimeStart()) == -1) {//当前时间 小于开始时间
            return new ResultUtil<Object>().setErrorMsg("未到投票时间");
        }
        if (new Date().compareTo(vote.getTimeEnd()) == 1) {//当前时间 大于结束时间
            return new ResultUtil<Object>().setErrorMsg("投票活动已结束");
        }
        String userid = securityUtil.getCurrUser().getId();
        String key = "votePraise::" + userid + ":" + voteId;

        if (redisClient.set().sIsMember(key, voteItemid)) {
            return new ResultUtil<Object>().setErrorMsg("请勿重复投票");
        }
        if (voteItemPraiseService.findByVoteIdAndVoteItemIdAndUserid(voteId, voteItemid, userid) == null) {
            VoteItemPraise voteItemPraise = new VoteItemPraise();
            voteItemPraise.setVoteId(voteId);
            voteItemPraise.setVoteItemId(voteItemid);
            voteItemPraise.setUserid(userid);
            voteItemPraiseService.save(voteItemPraise);
            iVoteItemService.incrPraiseCount(voteItemid);//增加投票数量
            redisClient.set().sAdd(key, voteItemid);//用户下 投票活动
            return new ResultUtil<Object>().setSuccessMsg("投票成功");
        } else {
            return new ResultUtil<Object>().setErrorMsg("请勿重复投票");
        }

    }


    @ApiOperation(value = "获取用户投票的明细ID集合")
    @PostMapping("getPraise/{voteId}")
    public Result<Object> getCollect(@PathVariable("voteId") String voteId) {

        String userid = securityUtil.getCurrUser().getId();
        String key = "votePraise::" + userid + ":" + voteId;
        Set<Object> set = redisClient.set().sMembers(key);
        if (set == null || CollUtil.isEmpty(set)) {
            Set<String> voteItemIds = iVoteItemPraiseService.findVoteItemIdByUseridAndVoteId(userid, voteId);
            if (CollUtil.isNotEmpty(voteItemIds)) {
                redisClient.set().sAdd(key, voteItemIds.toArray());
            }
            return new ResultUtil<Object>().setData(voteItemIds);
        }

        return new ResultUtil<Object>().setData(set);
    }
}
